// 品牌管理
import { Button, Card, Form, Input, Modal, Table, Upload, message } from 'antd'
import type { ColumnsType } from 'antd/lib/table'
import { PlusOutlined, EditOutlined, DeleteOutlined, LoadingOutlined } from "@ant-design/icons";
import React, { useEffect, useState } from 'react'
import { IReqListRecord } from '@/api/product/model/trademarkTypes';
import { ReqAddTrademark, ReqBaseTrademark, ReqEditTrademark, ReqTrademarkInfo, ReqDelTrademark } from '@/api/product/trademark';
import { useNavigate } from 'react-router-dom';
import { useForm } from 'antd/lib/form/Form'
import './index.less'
import type { RcFile, UploadChangeParam, UploadFile, UploadProps } from 'antd/es/upload/interface';

const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
};

const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('图片必须为jpg或png格式!');
    }

    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片大小不能超过2mb!');
    }
    return isJpgOrPng && isLt2M;
};

export default function Trademark() {
    //获取form
    let [form] = useForm();

    // 点击添加或编辑弹出对话框中图片logo
    const normFile = (e: any) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e?.fileList;
    };

    //获取 navigate函数
    // let navigate = useNavigate()

    //声明当前页码
    let [current, setCurrent] = useState<number>(1);

    //声明 总数
    let [total, setTotal] = useState<number>(0);

    //声明每页展示数据
    let [pageSize, setPageSize] = useState<number>(5);

    //声明 第页数
    let [page, setPage] = useState<number>(1);

    //每页展示几条
    let [limit, setLimit] = useState<number>(10);


    const [isModalOpen, setIsModalOpen] = useState(false);

    const [modaltitle, setmodaltitle] = useState<string>("编辑品牌")

    // 声明是新增还是修改
    const [isEdit, setisEdit] = useState(false)
    const [id, setid] = useState<number>()

    // 编辑按钮 显示并弹出对话框
    const showModal = async (id?: number) => {
        setid(id)
        setIsModalOpen(true);
        if (id) {
            setisEdit(true)
            // 详情
            const rusult = await ReqTrademarkInfo(id)
            // 赋值
            setImageUrl(rusult.data.logoUrl)
            form.setFieldsValue(rusult.data)
            setmodaltitle("编辑品牌")
        } else {
            setisEdit(false)
            setmodaltitle("新增品牌")
        }
    };

    //图片相关
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
    // 如果img有图片，就给它赋值
    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            setLoading(false)
            setImageUrl(info.file.response.data)
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );

    // 点击新增/编辑的确定按钮
    const handleOk = async () => {
        const tmName = form.getFieldValue("tmName")
        // console.log(tmName, imageUrl)
        const nameAddLogDate = {
            id: id,
            tmName: tmName as string,
            logoUrl: imageUrl as string,
        }
        // 关闭弹窗
        setIsModalOpen(false);
        // 判断是新增还是编辑
        isEdit ? await ReqEditTrademark(nameAddLogDate) : await ReqAddTrademark(nameAddLogDate)
        // 重新获取数据
        getTrademarkList(page, limit)
        // 提示信息
        message.success(isEdit ? "修改成功" : '新增成功')
    };

    // 监听弹框有没有展示，如果没有就清空
    useEffect(() => {
        if (!isModalOpen) {
            form.resetFields()
            setImageUrl('')
        }
    }, [isModalOpen])

    // 点击取消按钮
    const handleCancel = () => {
        // 关闭弹框 
        setIsModalOpen(false);
        form.resetFields()
    };

    
    // 删除品牌管理数据
    const delTradmark = async (id: number) => {
        // setid(id)
        const res = await ReqDelTrademark(id)
        console.log(res)
        getTrademarkList()
    }

    // 设置表头配置项
    const columns: ColumnsType<any> = [
        {
            title: '序号',
            width: 80,
            align: "center",
            render: (row, records, index) => index + 1
        },
        {
            title: '品牌名称',
            dataIndex: 'tmName',
            width: 150,
            align: "center"
        },
        {
            title: '品牌Logo',
            dataIndex: 'logoUrl',
            width: 150,
            align: "center",
            render: ((a) => {
                return <img src={a} alt="" width={80} />
            })
        },
        {
            title: "操作",
            align: "center",
            width: 150,
            render: (row: IReqListRecord) => {
                //当配置项存在  dataIndex 时，render第一个参数为对应的 dataIndex的值，第二个参数为这一行数据的对象，第三个参数 为下标
                //当配置项不存在 dataIndex时，render 第一个参数为这一行  数据对象
                return <>
                    <Button onClick={() => showModal(row.id)}
                        icon={<EditOutlined />} type='primary' size='small'>修改
                    </Button>
                    &emsp;
                    {/* onClick={del(row.id, row.hosname)} */}
                    <Button
                        className='ml'
                        danger icon={<DeleteOutlined />}
                        type='primary'
                        size='small'
                        onClick={() => delTradmark(row.id as number)}
                    >删除
                    </Button>
                </>
            },
            fixed: "right"//固定定位 固定到右边
        }
    ];

    //声明 品牌列表状态
    let [trademark, setTrademark] = useState<IReqListRecord[]>([])

    //获取品牌列表数据
    const getTrademarkList = async (page = current, limit = pageSize) => {
        setCurrent(page);
        setPageSize(limit)

        const res = await ReqBaseTrademark(page, limit)
        // console.log(res)
        // 更新品牌列表状态
        setTrademark(res.data.records)
        // 更新总数
        setTotal(res.data.total)

    }

    useEffect(() => {
        getTrademarkList(page, limit)
    }, [])

    return (

        <Card className='trademarkcard'>
            <Button
                onClick={() => showModal()}
                className='addbutton'
                type='primary'
                icon={<PlusOutlined />}
            >
                添加
            </Button>
            <Modal title={modaltitle} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <Form
                    form={form}
                    name='isEdit'
                    // onFinish={finish}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}

                >
                    <Form.Item
                        label="品牌名称"
                        name="tmName"
                        rules={[{ required: true, message: '品牌名称不能为空!' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item label="品牌Logo"
                        valuePropName="fileList"
                        getValueFromEvent={normFile}
                        rules={[{ required: true, message: '品牌Logo不能为空!' }]}
                    >
                        <Upload
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="/sph-api/admin/product/upload"
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                        >
                            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                    </Form.Item>
                </Form>
            </Modal>

            {/* 表格部分 */}
            <Table
                className='mt'
                columns={columns}
                dataSource={trademark}
                rowKey="id"
                bordered//边框
                // scroll={{ x: 1500 }}//滚动条
                pagination={{//分页器
                    total,//总数
                    pageSize,//每页展示数量
                    current,//当前页码
                    pageSizeOptions: [5, 10, 15, 20],//设置每页展示数据
                    showQuickJumper: true,//快速跳转至某页
                    showSizeChanger: true,//超过50条显示
                    showTotal: (total: number) => {//用于显示数据总量和当前数据顺序
                        return <span>总数：{total}条</span>
                    },
                    // 当页码或每页数量发生改变时触发
                    onChange: (page: number, pageSize: number) => {
                        //更新页码及每页展示数量状态
                        setCurrent(current);
                        setPageSize(pageSize)
                        getTrademarkList(page, limit)
                    }
                }}
            />
        </Card>
    )
}
